package com.mall.module.system.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.common.exception.BusinessException;
import com.mall.common.result.ResultCode;
import com.mall.module.system.domain.entity.SysConfig;
import com.mall.module.system.mapper.SysConfigMapper;
import com.mall.module.system.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 系统配置服务实现类
 */
@Service
public class SysConfigServiceImpl implements SysConfigService {

    @Autowired
    private SysConfigMapper configMapper;

    @Override
    public PageInfo<SysConfig> listConfigPage(Integer pageNum, Integer pageSize, String configKey, String configName) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysConfig> list = configMapper.selectConfigList(configKey, configName);
        return new PageInfo<>(list);
    }

    @Override
    public SysConfig getConfigByKey(String configKey) {
        return configMapper.selectConfigByKey(configKey);
    }

    @Override
    public SysConfig getConfigById(Long id) {
        return configMapper.selectConfigById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addConfig(SysConfig config) {
        // 检查键是否已存在
        SysConfig existConfig = configMapper.selectConfigByKey(config.getConfigKey());
        if (existConfig != null) {
            throw new BusinessException(ResultCode.DATA_ALREADY_EXISTED, "配置键已存在");
        }
        
        return configMapper.insertConfig(config) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateConfig(SysConfig config) {
        // 检查是否存在
        SysConfig existConfig = configMapper.selectConfigById(config.getId());
        if (existConfig == null) {
            throw new BusinessException(ResultCode.DATA_NOT_EXISTED, "配置不存在");
        }
        
        // 检查键是否重复（排除自身）
        SysConfig keyConfig = configMapper.selectConfigByKey(config.getConfigKey());
        if (keyConfig != null && !keyConfig.getId().equals(config.getId())) {
            throw new BusinessException(ResultCode.DATA_ALREADY_EXISTED, "配置键已存在");
        }
        
        return configMapper.updateConfig(config) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteConfig(Long id) {
        return configMapper.deleteConfigById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteConfigByIds(List<Long> ids) {
        return configMapper.deleteConfigByIds(ids) > 0;
    }
} 